#pragma once

/****************************************************
  Memory pools. Create and release game objects.
 ****************************************************/
template<class T>
class MemoryMag
{
public:
	MemoryMag(int size):
	  _maxSize(size),
	  _curSize(0),
	  _freedSize(0){
		  _data = new T[size];
		  _freed = new int[size];
	  }

	virtual ~MemoryMag(){
		delete [] _data;
		delete [] _freed;
	}

        // Get a new game object
        T * alloc(){
		if(!_freedSize){
			if(_curSize < _maxSize)
				return &_data[_curSize++];
			return 0;
		}
		return &_data[_freed[--_freedSize]];
	}

        // Free a game object
	int free(T * var){
		int i,j;
		int found = 0;
		for(j=0; j < _freedSize; ++j)
			if(&_data[_freed[j]] == var)
				found = 1;
		if(found)
			return 0;
		for(i=0; i < _curSize; ++i){
			if(&_data[i] == var){
				found = i;
				break;
			}
		}
		if(!found)
			return 0;
		if(found != (_curSize - 1)){
			_freed[_freedSize++] = found;
			return 1;
		}
		--_curSize;
		return 1;
	}

private:
	T * _data;
	int * _freed;
	int _freedSize;
	int _maxSize;
	int _curSize;
};

